package com.key.puzzlemodel

import android.app.Activity
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.webkit.*
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import com.key.puzzlemodel.config.PuzzleConfig
import com.key.puzzlemodel.databinding.ActivityWebScreenshotsBinding
import com.key.puzzlemodel.mvvm.BaseMVVMActivity
import com.key.puzzlemodel.mvvm.BaseMVVMViewModel
import com.key.puzzlemodel.util.BitmapUtil
import com.key.puzzlemodel.util.PuzzleAppManager
import kotlinx.coroutines.runBlocking

/**
 *
 * @功能描述:     网页截图界面
 * @创建时间:     2022/1/4
 * @创建者:       阳
 * @修改时间:     2022/1/4
 * @修改者:       阳
 */
class WebScreenshotsActivity :
    BaseMVVMActivity<ActivityWebScreenshotsBinding, BaseMVVMViewModel>(),
    View.OnClickListener {
    override val layoutId: Int?
        get() = R.layout.activity_web_screenshots


    //回调
    var intentActivityResultLauncher: ActivityResultLauncher<Intent>? = null

    override fun initView(savedInstanceState: Bundle?) {
        mVDB.clickListener = this
        //添加activity管理
        PuzzleAppManager.getInstance().addActivity(this)

        initWebView()
    }

    private fun initWebView() {
        mVDB.webScreenshots.settings.blockNetworkImage = false//解决图片不显示
        mVDB.webScreenshots.settings.javaScriptEnabled = true//解决图片不显示
        mVDB.webScreenshots.settings.domStorageEnabled = true
        mVDB.webScreenshots.settings.useWideViewPort = true
        mVDB.webScreenshots.settings.loadWithOverviewMode = true
        mVDB.webScreenshots.settings.domStorageEnabled = true
        mVDB.webScreenshots.settings.databaseEnabled = true
        mVDB.webScreenshots.settings.cacheMode = WebSettings.LOAD_NO_CACHE
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mVDB.webScreenshots.settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }


        //js通过window.androidObject.androidMethod()就可以直接调用安卓的androidMethod方法
        mVDB.webScreenshots.addJavascriptInterface(this, "android")
        mVDB.webScreenshots.loadData("", "text/html", "UTF-8")
        mVDB.webScreenshots.loadUrl(intent.getStringExtra("webAddress")!!)
        mVDB.webScreenshots.webChromeClient = object : WebChromeClient() {
            override fun onReceivedTitle(view: WebView, title: String) {
                super.onReceivedTitle(view, title)
                mVDB.txtTopTitle.text = view.title
            }
        }
        mVDB.webScreenshots.webViewClient = MyWebViewClient()


        intentActivityResultLauncher =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                //回调处理
                if (it.resultCode == Activity.RESULT_OK) {
                    it.data?.apply {
                        val mediaPath: String? = getStringExtra(PuzzleConfig.EDIT_RESULT)
                        //Log.e("返回数据：", "WebScreenshotsActivity == ${getStringExtra(PuzzleConfig.EDIT_RESULT)}")
                        setResult(Activity.RESULT_OK, Intent().apply {
                            putExtra(PuzzleConfig.EDIT_RESULT, mediaPath)
                        })
                        this@WebScreenshotsActivity.finish()
                    }
                }
            }
    }

    @JavascriptInterface
    fun testTodo() {
    }

    private inner class MyWebViewClient : WebViewClient() {
        override fun shouldOverrideUrlLoading(
            view: WebView?,
            request: WebResourceRequest?
        ): Boolean {
            return super.shouldOverrideUrlLoading(view, request)
        }
    }


    override fun onClick(v: View) {
        when (v.id) {
            R.id.image_return -> {
                onBackPressed()
            }
            R.id.txt_top_title_right -> { //截图
//                var btimap = BitmapUtil.getWebViewBitmap(this, mVDB.webScreenshots)
                saveBitmap()
            }
        }
    }

    fun saveBitmap() {
        runBlocking {

            //https://blog.csdn.net/hailong0529/article/details/88677358
            PuzzleConfig.saveBitmap = BitmapUtil.captureWebView(mVDB.webScreenshots)
            if (null == PuzzleConfig.saveBitmap) {
                Toast.makeText(this@WebScreenshotsActivity, "图片内容过多，暂时无法截图", Toast.LENGTH_SHORT)
                    .show()
                return@runBlocking
            }
            val intent = Intent(this@WebScreenshotsActivity, SaveBitmapActivity::class.java)
//                val baos = ByteArrayOutputStream()
//                btimap!!.compress(Bitmap.CompressFormat.PNG, 100, baos)
//                val bitmapByte: ByteArray = baos.toByteArray()
//                intent.putExtra(PuzzleConfig.SAVE_PHOTO, bitmapByte)
            intentActivityResultLauncher?.launch(intent)
        }

    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && mVDB.webScreenshots.canGoBack()) {
            mVDB.webScreenshots.goBack()//返回上个页面
            return true
        }
        return super.onKeyDown(keyCode, event)
    }
}



















